﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace Treasure.Client
{
    public  class MyConvert
    {

        /// <summary>
        /// 用utf-8 把string转换成 byte格式的string 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToBStr(string str)
        {
            string StrBy = "";
            if (str == "") return StrBy;
            //byte bys = Convert.ToByte(str);
            byte[] byteStr = Encoding.UTF8.GetBytes(str);
            for (int i = 0; i < byteStr.Length; i++)
            {
                StrBy += byteStr[i].ToString() + " ";
            }
            return StrBy;
        }
        /// <summary>
        /// 用utf-8 把byte格式的string转换成  string
        /// </summary>
        /// <param name="strb"></param>
        /// <returns></returns>
        public static string ToStrB(string strb)
        {
            string str = "";
            if (strb == "") return str;
            string[] Bstr = strb.Split(' ');
            byte[] byteStr = new byte[Bstr.Length];
            for (int i = 0; i < Bstr.Length; i++)
            {
                if (Bstr[i] != "")
                    byteStr[i] = Convert.ToByte(Bstr[i]);
            }
            str = Encoding.UTF8.GetString(byteStr);
            return str;
        }

        /// <summary>
        /// RTF转字符串
        /// </summary>
        /// <param name="richTextBox"></param>
        /// <returns></returns>
        public static string RTF(RichTextBox richTextBox)
        {
            string rtf = string.Empty;
            TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream ms = new MemoryStream())
            {
                textRange.Save(ms, DataFormats.Rtf);
                ms.Seek(0, SeekOrigin.Begin);
                StreamReader sr = new StreamReader(ms);
                rtf = sr.ReadToEnd();
            }

            return rtf;
        }
        /// <summary>
        /// richTextBox 复制
        /// </summary>
        /// <param name="richTextBox"></param>
        /// <param name="rtf"></param>
        public static void LoadFromRTF(RichTextBox richTextBox, string rtf)
        {

            TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    sw.Write(rtf);
                    sw.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    textRange.Load(ms, DataFormats.Rtf);
                }
            }
        }
    }
}
